<template>
<view>
<view class="container" v-if="firstCategoris && firstCategoris.length > 0">
    <view class="nav">
        <view v-for="(item, index) in firstCategoris" :key="index" :class="'nav-item ' + (item.id==currentCategoryId?'nav-item-on':'')" @tap="switchFirstCategory" :data-id="item.id" :data-index="index">{{item.mobile_name}}</view>
    </view>
    <view class="content">
       <view class="content-box" v-if="adv.ad_code" @tap.stop="adver" :data-url="adv.ad_link" :data-type="adv.media_type">
          <image :src="url + adv.ad_code" class="adver-image"></image>
       </view>
        <view class="content-box" :key="index">
            <block v-for="(item, index) in categories" :key="index">
                <view class="content-name" @tap="goodsList" :data-id="item.id">{{item.mobile_name}}</view>
                <view class="content-items" v-if="item.sub_category.length>0">
                    <navigator v-for="(item, index2) in item.sub_category" :key="index2" class="content-item" :url="'/pages/goods/goodsList/goodsList?cat_id=' + item.id">
                        <image class="item-image" :src="item.image?url+item.image:'../../../images/unknow.png'"></image>
                        <view class="item-name">{{item.mobile_name}}</view>
                    </navigator>
                </view>
            </block>

            <block v-if="types ==2&&categorys2.length>0">            
             <view class="two-content">
                <view class="separate">                  
                        <view v-for="(item, index) in categorys2" :key="index" class="t-list">
                            <navigator :url="'/pages/goods/goodsList/goodsList?cat_id=' + item.id">
                                <image :src="item.image?url+item.image:'../../../images/unknow.png'"></image>
                                    <text>{{item.mobile_name}}</text>
                            </navigator>
                        </view>        
                  </view>
                </view>
            </block>


            <block v-if="types==3&&goods.length>0">
                    <view class="one-content">
                    <view v-for="(item, index) in goods" :key="index" class="cmd-list">
                        <navigator :url="'/pages/goods/goodsInfo/goodsInfo?goods_id=' + item.goods_id" class="cmd-img"><image :src="item.original_img?url+item.original_img:'../../../images/red-icon-cart.png'"></image></navigator>
                        <view class="cmd-comm cmd-title">
                            <view>
                            <navigator :url="'/pages/goods/goodsInfo/goodsInfo?goods_id=' + item.goods_id" class="str-product">{{item.goods_name|| '暂无名称'}}</navigator>
                            <text class="str-prices">￥{{item.shop_price || 0}}元</text>
                            <view class="str-evaluate">
                                <text class="fg">{{item.comment_count || 0}}条评价</text>
                                <text class="fg"></text>
                                <view class="add-cart"><image @tap.stop="openSpecModel" :data-goods_id="item.goods_id" src="/static/images/red-icon-cart.png"></image></view>
                            </view>
                            </view>
                        </view>
                      </view>            
                    </view>
            </block>

        </view>
    </view>
</view>

<view class="no-data" v-if="!firstCategoris || firstCategoris.length == 0">
    <image src="/static/images/cart-null.png" class="cart-image"></image>
    <view class="no-data-title">暂无分类</view>
    <navigator url="/pages/index/index/index" class="lookat"> 去逛逛 </navigator>
</view>





<!-- 规格弹窗 -->
<view :hidden="!openSpecModal">
    <view class="cover-layer" @tap="closeSpecModal"></view>
    <view class="spec-model">
        <icon type="cancel" color="gray" size="22" class="modal-close" @tap="closeSpecModal"></icon>
        <view class="spec-goods">
            <image class="wh100 spec-img" :src="url + '/api/goods/goodsThumImages?goods_id=' + data.goods.goods_id + '&width=200&height=200'"></image>
            <view class="spec-goods-info">
                <view class="spec-goods-name">{{data.goods.goods_name}}</view>
                  <view class="prom-info" v-if="select.activity.prom_type && select.activity.prom_type != 6">
                    <text class="prom-type">{{select.activity.countName}}</text>
                    <text>{{select.activity.countTime}}</text>
                </view>
                 <navigator class="prom-info" v-if="select.activity.prom_type == 6" :url="'../../team/team_info/team_info?goods_id=' + select.activity.goods_id + '&team_id=' + select.activity.team_id + '&item_id=' + select.activity.item_id">
                    <text class="prom-type">{{select.activity.countName}}</text>
                    <view style="display:inline-block;">点击前往</view>
                </navigator>
                <view class="spec-goods-price">￥ {{select.price}}
                </view>
                <view class="spec-goods-stock">剩余库存：{{select.stock}}</view>
            </view>
        </view>
        <view class="spec-name">数量</view>
        <view class="count">
            <view class="sub" @tap="subCartNum">-</view>
            <input type="number" :value="goodsInputNum" @blur="inputCartNum"></input>
            <view class="add" @tap="addCartNum">+</view>
        </view>
        <block v-for="(item, listIdx) in data.goods_spec_list" :key="listIdx">
            <view class="spec-name">{{item.name}}</view>
            <view v-for="(spec, index) in item.spec_item" :key="index" :class="'spec-btn ' + (item.selectItemId==spec.id?'spec-btn-click':'')" @tap="selectSpec" :data-listidx="listIdx" :data-itemid="spec.id">{{spec.item}}</view>
        </block>
        <view class="spec-cart-btns">
                <view v-if="data.goods.is_virtual" :class="'spec-cart-btn spec-buy spec-cart-btn-lg ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" data-action="buy" @tap="addCart">立即购买</view>
                 <block v-else-if="select.activity.prom_type == 8">                
                        <view :class="'spec-cart-btn spec-buy spec-cart-btn-lg ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" @tap="bargainBuy" data-action="add" :data-status="isSeparate">{{isSeparate?'砍价拿':'加入购物车'}}</view>                   
            </block>
                 <view v-else-if="select.activity.prom_type == 4" :class="'spec-cart-btn spec-buy spec-cart-btn-lg ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" data-action="reserve" @tap="addCart">立即预订</view>
            <block v-else-if="data.goods.exchange_integral <= 0">
                <view :class="'spec-cart-btn spec-add-cart ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" data-action="add" @tap="addCart">加入购物车</view>
                <view :class="'spec-cart-btn spec-buy ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" data-action="buy" @tap="addCart">立即购买</view>
            </block>
            <view v-else :class="'spec-cart-btn spec-buy spec-cart-btn-lg ' + (select.stock<=0||shippingCost<0||!hasSpec?'spec-cart-disable':'')" data-action="exchange" @tap="addCart">立即兑换</view>
        </view>
    </view>
</view>




<!-- 底部菜单 -->
<!--<import src="../../index/publics/publics.wxml"></import>-->
<block data-type="template" data-is="model" data-attr="page:menu_index,menu_model:menu_model,url:url,defaultMenu:defaultMenu">
<!-- 底部菜单 -->
<view class="pos_fixed">
    <view class="tpd-footer tpd-footer2" v-if="menu_model.length>0">
       <block v-for="(item, index) in menu_model" :key="index">
        <view hover-class="none" @tap.stop="topage" data-obj="custom" :data-idx="index" :class="menu_index == index ? 'tpd-footer-select' : ''"><image :src="menu_index == index ? url + item.pic2 : url + item.pic1"></image><text :style="'color:' + (menu_index == index ? item.navFontColor : '')">{{item.title_name}}</text></view>  
        </block> 
    </view>

    <view class="tpd-footer tpd-footer1" v-if="defaultMenu">
        <view hover-class="none" @tap.stop="topages" data-idx="0" :class="menu_index == 0 ? 'tpd-footer-select' : ''"><image :src="menu_index == 0 ? '/images/home2.png' : '/images/home1.png'"></image><text>首页</text></view>
        <view hover-class="none" @tap.stop="topages" data-idx="1" :class="menu_index == 1 ? 'tpd-footer-select' : ''"><image :src="menu_index == 1 ? '/images/category2.png' : '/images/category1.png'"></image><text>分类</text></view>
        <view hover-class="none" @tap.stop="topages" data-idx="4" :class="menu_index == 4 ? 'tpd-footer-select' : ''"><image :src="menu_index == 4 ? '/images/play2.png' : '/images/play1.png'"></image><text>直播</text></view>
        <view hover-class="none" @tap.stop="topages" data-idx="2" :class="menu_index == 2 ? 'tpd-footer-select' : ''"><image :src="menu_index == 2 ? '/images/cart2.png' : '/images/cart1.png'"></image><text>购物车</text></view>
        <view hover-class="none" @tap.stop="topages" data-idx="3" :class="menu_index == 3 ? 'tpd-footer-select' : ''"><image :src="menu_index == 3 ? '/images/user2.png' : '/images/user1.png'"></image><text>我的</text></view>
    </view>
  </view>
</block>
</view>
</template>

<script>
var app = getApp();
var request = app.globalData.request;
var common = require("../../../utils/common.js");
var util = require("../../../utils/util.js");

export default {
  data() {
    return {
      url: app.globalData.setting.url,
      firstCategoris: [],
      categories: [],
      currentCategoryId: 0,
      //目前的第一分类id
      scrollHeight: 0,
      //界面高度，用于滚动
      defaultMenu: false,
      //默认底部菜单显示状态
      types: 1,
      //分类风格 1 2 3 
      categorys2: [],
      goods: [],
      datas: [],
      openSpecModal: false,
      //是否打开规格弹窗
      goodsInputNum: 1,
      //选中的商品件数
      specSelect: 0,
      //选中的组合规格数组spec_goods_price下标
      optionItemId: 0,
      //页面参数，页面初始化指定显示的itemid，用于活动
      shippingCost: 0,
      hasSpec: true,
      select: {
        //选择的(规格)商品的参数，用于显示
        price: 0,
        stock: 0,
        specName: '',
        activity: null
      },
      isBragain: false,
      isSeparate: true,
      menu_index: "",
      menu_model: "",
      webUrl: "",
      adv: "",
      enterAddressPage: false,
      data: ""
    };
  },

  components: {},
  props: {},
  onLoad: function () {
    var types = common.getConfigByName(app.globalData.config['config'], 'category_switch') || 1;
    console.log(types);

    if (types == 1) {
      this.requestFirstCategoris();
    } else if (types == 2) {
      this.requestCategoris(2);
    } else {
      this.requestCategoris(3);
    }

    if (app.globalData.menu_model.length == 0) {
      app.globalData.menu_index = 1;
    } else {
      //遍历自定义底部，该页面在哪个位置
      for (var i in app.globalData.menu_model) {
        if (app.globalData.menu_model[i].app_url.indexOf('categoryList') != -1) {
          app.globalData.menu_index = i;
        }
      }
    }

    this.setData({
      types: types,
      defaultMenu: app.globalData.defaultMenu,
      menu_index: app.globalData.menu_index,
      menu_model: app.globalData.menu_model
    });
  },
  methods: {
    //请求分类
    requestCategories: function (parenId) {
      var that = this;
      request.get('/api/goods/goodsSecAndThirdCategoryList', {
        data: {
          'parent_id': parenId
        },
        success: function (res) {
          that.setData({
            categories: res.data.result,
            currentCategoryId: parenId
          });
        }
      });
    },
    adver: function (e) {
      common.adverPage(e.currentTarget.dataset.type, e.currentTarget.dataset.url, this);
    },
    //切换第一分类
    switchFirstCategory: function (e) {
      this.changeType(e.currentTarget.dataset.id, e.currentTarget.dataset.index);
    },
    goodsList: function (e) {
      var catId = e.currentTarget.dataset.id;
      uni.navigateTo({
        url: '/pages/goods/goodsList/goodsList?cat_id=' + catId
      });
    },

    /** 跳转模式 自定义页面 || 自定义菜单 || 自定义控件控件*/
    topage(e) {
      //自定义菜单
      var idx = e.currentTarget.dataset.idx;
      app.globalData.menu_index = idx;
      var page_type = this.menu_model[idx].url_type;
      var id = this.menu_model[idx].app_url; //判断跳转的类型  0 = 外部网址,1 = 小程序页面，2 = 分类商品，3 = 商品详情 ，4 = 自定义页面

      if (page_type == 1) {
        //要访问的页面idx，当前页面menu_index
        common.totabar(idx, this.menu_index, this.menu_model);
      } else if (page_type == 2) {
        uni.navigateTo({
          url: '/pages/goods/goodsList/goodsList?cat_id=' + id
        });
      } else if (page_type == 3) {
        uni.navigateTo({
          url: '/pages/goods/goodsInfo/goodsInfo?goods_id=' + id
        });
      } else if (page_type == 0) {
        this.setData({
          webUrl: id
        });
        uni.navigateTo({
          url: '/pages/index/webview/webview'
        });
      } else {
        uni.reLaunch({
          url: '../../index/customPage/customPage?id=' + this.menu_model[idx].app_url
        });
      }
    },

    changeType: function (id, index) {
      var that = this;

      if (that.types == 1) {
        that.requestCategories(id);
      } else if (that.types == 2) {
        that.categoryHandle(that.datas, index);
      } else {
        that.categoryHandle(that.datas, index);
      }
    },

    /** 默认菜单 */
    topages: function (e) {
      var idx = e.currentTarget.dataset.idx;
      app.globalData.menu_index = idx;
      common.defaultTotabar(idx, 1);
    },
    requestFirstCategoris: function () {
      var that = this;
      request.get('/api/goods/goodsCategoryList', {
        isShowLoading: false,
        data: {
          new_ad: 1
        },
        success: function (res) {
          var categories = res.data.result.category;

          if (categories.length == 0) {
            return;
          }

          that.setData({
            firstCategoris: categories,
            adv: res.data.result.adv
          });
          that.requestCategories(categories[0].id);
        }
      });
    },
    requestCategoris: function (types) {
      var that = this;
      request.get('/api/goods/categoryPage?category=' + types, {
        success: function (res) {
          if (res.data.status == 1) {
            that.setData({
              datas: res.data
            });
            that.categoryHandle(res.data);
          }
        }
      });
    },

    /** 处理分类 */
    categoryHandle: function (datas, index) {
      var that = this;
      var idx = !index ? 0 : index;
      that.setData({
        firstCategoris: datas.category1,
        currentCategoryId: datas.category1[idx]['id']
      });

      if (that.types == 2) {
        let category2 = datas.category2;
        let categorys2 = [];

        for (var i = 0; i < category2.length; i++) {
          if (category2[i]['parent_id'] == datas.category1[idx]['id']) {
            categorys2.push(category2[i]);
          }
        }

        that.setData({
          categorys2: categorys2
        });
      }

      if (that.types == 3) {
        let good = datas.goods;
        let goods = [];

        for (var i = 0; i < good.length; i++) {
          if (good[i]['cat_id'] == datas.category1[idx]['id']) {
            goods.push(good[i]);
          }
        }

        that.setData({
          goods: goods
        });
      }
    },

    /** 规格相关s */

    /** 购买虚拟商品 */
    buyVirtualGoods: function (data) {
      //检查用户是否登录方可操作立即购买
      if (!app.globalData.auth.isAuth()) {
        app.globalData.showLoading(null, 1500);
        app.globalData.getUserInfo();
        return;
      }

      Object.assign(data, {
        goods_name: this.data.goods.goods_name,
        spec_name: this.select.specName,
        price: this.select.price
      });
      uni.navigateTo({
        url: '/pages/virtual/buy_step/buy_step?' + util.Obj2Str(data)
      });
    },

    /** 立即兑换 */
    exchange: function (data) {
      //检查用户是否登录方可操作立即购买
      if (!app.globalData.auth.isAuth()) {
        app.globalData.showLoading(null, 1500);
        app.globalData.getUserInfo();
        return;
      }

      if (app.globalData.userInfo.pay_points < this.data.goods.exchange_integral) {
        return app.globalData.showTextWarining('您的积分不够喔~');
      }

      if (this.shippingCost < 0 || this.select.stock <= 0 || !this.hasSpec) {
        return;
      }

      this.setData({
        openSpecModal: false,
        enterAddressPage: true
      });
      uni.navigateTo({
        url: '/pages/cart/integral/integral?' + util.Obj2Str(data)
      });
    },

    /** 立即预订 */
    reserve: function (data) {
      var that = this; //检查用户是否登录方可操作立即购买

      if (!app.globalData.auth.isAuth()) {
        app.globalData.showLoading(null, 1500);
        app.globalData.getUserInfo();
        return;
      }

      if (this.shippingCost < 0 || this.select.stock <= 0 || !this.hasSpec) {
        return;
      }

      Object.assign(data, {
        action: 'reserve',
        prom_id: that.select.activity.prom_id ? that.select.activity.prom_id : ''
      });
      this.setData({
        openSpecModal: false,
        enterAddressPage: true
      });
      uni.navigateTo({
        url: '/pages/cart/reserve/reserve?' + util.Obj2Str(data)
      });
    },

    /** 立即购买 */
    buyNow: function (data) {
      //检查用户是否登录方可操作立即购买
      if (!app.globalData.auth.isAuth()) {
        app.globalData.showLoading(null, 1500);
        app.globalData.getUserInfo();
        return;
      }

      if (this.shippingCost < 0 || this.select.stock <= 0 || !this.hasSpec) {
        return;
      }

      Object.assign(data, {
        action: 'buy_now'
      });
      this.setData({
        openSpecModal: false,
        enterAddressPage: true
      });
      uni.navigateTo({
        url: '/pages/cart/cart2/cart2?' + util.Obj2Str(data)
      });
    },

    /** 关闭规格弹窗 */
    closeSpecModal: function () {
      this.setData({
        openSpecModal: false
      });
    },

    /** 打开规格弹窗 */
    openSpecModel: function (e) {
      var that = this;
      request.get('/api/goods/goodsInfo', {
        data: {
          id: e.currentTarget.dataset.goods_id
        },
        failRollback: true,
        success: function (res) {
          that.setData({
            data: res.data.result,
            openSpecModal: true
          });
          that.initData(res.data.result);
        }
      });
    },

    /** 初始化数据，注意顺序 */
    initData: function (data) {
      //检查商品
      this.initCheckGoods(data); //检查一下购物的数量，可能无库存

      this.checkCartNum(this.goodsInputNum);
    },

    /** 检查商品 */
    initCheckGoods: function (data) {
      var that = this;
      request.post('/api/goods/activity', {
        data: {
          goods_id: data.goods.goods_id,
          item_id: data.goods.spec_goods_price.length > 0 ? data.goods.spec_goods_price[0]['item_id'] : ''
        },
        success: function (res) {
          //初始化规格
          if (res.data.result.goods.activity_is_on == 1) {
            that.initSpecsPrice(res.data.result);
          } else {
            data.goods.prom_type = 0;
            that.initSpecsPrice(data);
          }
        }
      });
    },

    /** 初始化所有规格 */
    initSpecsPrice: function (data) {
      var specSelect = 0; //初始化选中第一个规格 

      var specs = this.data.goods.spec_goods_price;

      if (specs.length == 0) {
        //没有规格
        this.initActivity(data.goods);
        return;
      } //第一次请求的总数据中的activity默认是第一种规格的,可减少一次请求
      //specs[0].activity = data.goods;
      // if (this.data.optionItemId) { //指定规格
      //     for (var i = 0; i < specs.length; i++) {
      //         if (specs[i].item_id == this.data.optionItemId) {
      //             specSelect = i;
      //             break;
      //         }
      //     }
      // } else { //初始化选库存不为0的规格
      //     for (var i = 0; i < specs.length; i++) {
      //         if (specs[i].store_count <= 0) {
      //             continue;
      //         }
      //         specSelect = i;
      //         break;
      //     }
      // }
      // specs[specSelect].activity = data.goods;
      //生成子规格组(goods_spec_list)的各自选中项


      var specIds = specs[specSelect].key.split("_");
      var list = this.data.goods.spec;
      this.initSelectSpecGoods();
    },

    /** 初始化选中的规格商品 */
    initSelectSpecGoods: function () {
      var specSelect = this.specSelect;
      var specs = this.data.goods.spec_goods_price;
      var itemId = specs[specSelect].item_id;

      if (specs[specSelect].prom_type == 0) {
        var noActivity = {
          prom_type: 0
        };
        specs[specSelect].activity = noActivity;
        this.initActivity(noActivity);
      } else if (typeof specs[specSelect].activity != 'undefined') {
        this.initActivity(specs[specSelect].activity);
      } else {
        this.requestSpecInfo(specSelect);
      }
    },

    /** 点击规格按钮的回调函数 */
    selectSpec: function (e) {
      //对商品数量进行判断，对库存进行判断
      var itemId = e.currentTarget.dataset.itemid;
      var listIdx = e.currentTarget.dataset.listidx;
      var list = this.data.goods_spec_list;

      if (list[listIdx].selectItemId == itemId) {
        return;
      }

      list[listIdx].selectItemId = itemId;
      var newSpecKeys = [];

      for (var i = 0; i < list.length; i++) {
        newSpecKeys[i] = list[i].selectItemId;
      } //item排序,生成key


      var newSpecKeys = util.sortSize(newSpecKeys).join('_');
      var newSpecSelect = 0;
      var specs = this.data.goods.spec_goods_price;
      var hasSpec = false;

      for (var i = 0; i < specs.length; i++) {
        if (specs[i].key == newSpecKeys) {
          hasSpec = true;
          newSpecSelect = i;
          break;
        }
      }

      this.setData({
        hasSpec: hasSpec,
        specSelect: newSpecSelect,
        'data.goods_spec_list': list,
        isBragain: this.isSeparate ? false : true
      });
      this.initSelectSpecGoods();
      this.checkCartNum(this.goodsInputNum);
    },

    /** 初始化显示的活动信息 */
    initActivity: function (activity) {
      if (activity.prom_type && activity.prom_type != 6) {
        var startTime = new Date().getTime();

        if (activity.prom_type == 1) {
          //抢购
          activity.priceName = '抢购价';
          activity.countName = '限时抢购';
        } else if (activity.prom_type == 2) {
          //团购
          activity.priceName = '团购价';
          activity.countName = '限时团购';
        } else if (activity.prom_type == 3) {
          //促销
          activity.countName = '优惠促销';
        } else if (activity.prom_type == 4) {
          //预售
          activity.priceName = '预售价';
          activity.countName = '预售商品';
        } else if (activity.prom_type == 8) {
          //砍价
          !this.isBragain ? activity.priceName = '砍价享' : activity.priceName = '';
          !this.isBragain ? activity.countName = '砍价活动' : activity.countName = '';
        }

        activity.countTime = '--天--时--分--秒';

        if (!activity.diffTime) {
          activity.diffTime = new Date().getTime() - activity.server_current_time * 1000;
        }
      } else if (activity.prom_type == 6) {
        activity.countName = '该商品正在参与拼团';
        activity.goods_id = activity.goods_id;
        activity.team_id = activity.prom_id ? activity.prom_id : 0;
        activity.item_id = activity.item_id ? activity.item_id : 0;
      }

      this.setData({
        'select.activity': activity
      });
      this.destroyActivityTimer();
      this.createActivityTimer();
      this.initSelectedData();
    },

    /** 初始化选中的（规格）商品的显示参数 */
    initSelectedData: function () {
      var goods = this.data.goods;
      var activity = this.select.activity;
      var specs = this.data.goods.spec_goods_price;
      var specSelect = this.specSelect;
      var stock = 0;
      var price = 0;

      if (activity.prom_type == 1 || activity.prom_type == 2) {
        price = activity.shop_price;
        stock = activity.store_count;
      } else if (activity.prom_type == 3) {
        price = activity.shop_price; // stock = specs.length > 0 ? specs[specSelect].store_count : goods.store_count;

        stock = activity.store_count;
      } else if (activity.prom_type == 4) {
        price = activity.shop_price; //stock = specs.length > 0 ? specs[specSelect].store_count : goods.store_count;

        stock = activity.store_count;
      } else if (activity.prom_type == 8 && !this.isBragain) {
        price = activity.end_price ? activity.end_price : activity.shop_price;
        stock = activity.store_count;
        this.setData({
          'select.bargain_price': price
        });
      } else if (specs.length > 0) {
        price = specs[specSelect].price;
        stock = specs[specSelect].store_count;
      } else {
        price = goods.shop_price;
        stock = goods.store_count;
      }

      this.setData({
        'select.price': price,
        'select.stock': stock,
        'select.specName': specs.length > 0 ? specs[specSelect].key_name : ''
      });

      if (this.isBragain) {
        this.setData({
          isBragain: false
        });
      }
    },

    /** 检查是否倒计时是否结束 */
    checkActivityTime: function () {
      var that = this;
      var activity = that.select.activity;
      var remainTime = activity.end_time * 1000 - new Date().getTime() + activity.diffTime;

      if (remainTime > 0) {
        remainTime = util.remainTime(remainTime);
        that.setData({
          'select.activity.countTime': remainTime
        });
      } else {
        that.requestSpecInfo(that.specSelect);
        return;
      }
    },

    /** 创建活动倒计时定时器 */
    createActivityTimer: function () {
      var that = this;
      var activity = that.select.activity;

      if (!activity.prom_type || activity.prom_type == 6 || that.isBragain) {
        return;
      }

      that.timer = setInterval(function () {
        that.checkActivityTime();
      }, 1000);
    },

    /** 销毁活动倒计时定时器 */
    destroyActivityTimer: function () {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    /** 请求规格商品的活动信息 */
    requestSpecInfo: function (specSelect) {
      var that = this;
      var specs = that.data.goods.spec_goods_price;
      request.get('/api/goods/activity', {
        data: {
          goods_id: that.data.goods.goods_id,
          item_id: specs.length > 0 ? specs[specSelect].item_id : ''
        },
        success: function (res) {
          if (res.data.result.goods.activity_is_on == 1) {
            that.initActivity(res.data.result.goods);
          }
        }
      });
    },

    /** 减少购买的商品数量 */
    subCartNum: function (e) {
      this.checkCartNum(this.goodsInputNum - 1);
    },

    /** 增加购买的商品数量 */
    addCartNum: function (e) {
      this.checkCartNum(this.goodsInputNum + 1);
    },

    /** 输入购买的数量 */
    inputCartNum: function (e) {
      this.checkCartNum(Number(e.detail.value));
    },

    /** 检查购买的数量 */
    checkCartNum: function (num) {
      var specs = this.data.goods.spec_goods_price;
      var specSelect = this.specSelect;
      var activity = this.select.activity;
      var stock = this.data.goods.store_count; //参与活动

      if (activity && activity.activity_is_on == 1) {
        stock = activity.store_count;
      } else {
        if (specs.length > 0) {
          stock = specs[specSelect].store_count;
        }
      }

      if (num > stock || stock == 0) {
        num = stock;
      } else if (num < 1) {
        num = 1;
      }

      this.setData({
        goodsInputNum: num
      });
    },

    /** 加入购物车 */
    addCart: function (e) {
      console.log('触发了点击事件');
      var that = this;
      var itemId = 0;
      var specs = this.data.goods.spec_goods_price; //区分有规格和无规格

      if (specs.length > 0) {
        if (specs[this.specSelect].store_count <= 0) {
          return app.globalData.showTextWarining("当前无库存！");
        }

        itemId = specs[this.specSelect].item_id;
      } else {
        if (this.data.goods.store_count <= 0) {
          return app.globalData.showTextWarining("当前无库存！");
        }
      }

      if (this.goodsInputNum <= 0) {
        return app.globalData.showTextWarining("商品数量不能小于1");
      }

      var data = {
        goods_id: this.data.goods.goods_id,
        goods_num: this.goodsInputNum,
        item_id: itemId
      };

      if (this.data.goods.is_virtual) {
        return this.buyVirtualGoods(data);
      }

      if (e.currentTarget.dataset.action == 'add') {
        //加入购物车
        console.log('add');

        if (this.shippingCost < 0 || this.select.stock <= 0 || !this.hasSpec) {
          return;
        }

        request.post('/api/cart/add', {
          data: data,
          success: function (res) {
            that.setData({
              openSpecModal: false
            });
            request.checkUniqueId();
            app.globalData.showSuccess('添加成功');
          }
        });
      } else if (e.currentTarget.dataset.action == 'exchange') {
        //立即兑换
        this.exchange(data);
      } else if (e.currentTarget.dataset.action == 'reserve') {
        //立即预订
        this.reserve(data);
      } else {
        //立即购买
        this.buyNow(data);
      }
    },

    /** 砍价购买 */
    bargainBuy: function (e) {
      var that = this;

      if (!app.globalData.auth.isAuth()) {
        app.globalData.showLoading(null, 1500);
        app.globalData.getUserInfo();
        return;
      }

      var data = e.currentTarget.dataset;

      if (data.status) {
        //砍价拿
        that.setData({
          openSpecModal: false
        });
        var specs = that.data.goods.spec_goods_price;
        var specSelect = that.specSelect;
        var item_id = specs.length > 0 ? specs[specSelect]['item_id'] : '';

        if (that.select.stock == 0 || Number(that.select.stock) - Number(that.goodsInputNum) < 0) {
          that.setData({
            goodsInputNum: 1
          });
          return app.globalData.showTextWarining('砍价库存不足!');
        }

        uni.showModal({
          content: '确定发起砍价吗?',
          success: function (res) {
            if (res.confirm) {
              //去下单，并且发起砍价活动
              request.post('/api/Bargain/start_bargain', {
                data: {
                  bargain_id: that.select.activity.prom_id,
                  goods_num: that.goodsInputNum,
                  item_id: item_id
                },
                success: function (res) {
                  if (1 == res.data.status) {
                    uni.navigateTo({
                      url: '/pages/Bargain/bargain/bargain?id=' + res.data.result.id
                    });
                  } else {
                    app.globalData.showTextWarining(res.data.msg);
                  }
                }
              });
            }
          }
        });
      } else {
        //单独购
        that.addCart(e);
      }
    }
    /** 规格相关e */

  }
};
</script>
<style>
.container{
    flex-direction: row;
}
.nav{
    width: 20%;
    height:100%;
    font-size: 28rpx;
    text-align: center;
    box-sizing: border-box;
    display: inline-block;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    overflow-x: hidden;
    padding-bottom:134rpx;
    background-color:white;
}
.adver-image{
    width:100%;
    height:180rpx;
    display:inline-block;
    overflow:hidden;
}
.nav-item{
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    padding: 25rpx 10rpx;
    border-bottom: 1rpx solid #f3f3f3;
    background-color: white;
    text-overflow: ellipsis;
    font-size: 28rpx;
}
.nav-item-on{
    color: #ff6a00;
    position: relative;
}
.nav-item-on::before{
  content: "";
  width: 8rpx;
  height: 100%;
  position: absolute;
  left: 0rpx;
  top: 0rpx;
  background: #ff6a00;
}
.content{
    width: 80%;
    height:100%;
    font-size: 28rpx;
    padding: 0 15rpx;
    box-sizing: border-box;
    display: inline-block;
    position: fixed;
    top: 0;
    bottom: 0;
    right: 0;
    overflow-x: hidden;
}
.content-box:last-of-type{
    margin-bottom:134rpx;
}
nav-item:last-of-type{
    margin-bottom:134rpx;
}
.content-name{
    margin: 30rpx 0 20rpx;
    padding-left: 10rpx;
}
.content-items{
    background-color: white;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    width: 100%;
    border-radius: 10rpx;
}
.content-item{
    width: 33.333333%;
    box-sizing: border-box;
    padding: 10rpx;
    word-break: keep-all;
    white-space: nowrap;
    overflow: hidden;
    display: inline-block;
    text-align: center;
}
.item-image{
    width: 100rpx;
    height: 100rpx;
}
.item-name{
    padding: 10rpx 0;
    font-size: 24rpx;
    color: #666666;
    background-color:white;
    text-overflow:ellipsis;
    white-space:nowrap;
    width: 160rpx;
    overflow: hidden;
}


/** 二级分类 **/

.two-content{
  width:100%;
  height:100%;
  font-size:28rpx;
  box-sizing:border-box;
  display:inline-block;
  position:absolute;
  top:0;
  bottom:0;
  right:0;
  overflow-x:hidden;
  padding-bottom:133px;
  padding-left: 20rpx;
}

.t-list{
  width: 181rpx;
  height: 181rpx;
  margin-top: 10rpx;
  float: left;
  margin-right: 10rpx;
  text-align: center;
  background: #fff;
  border-radius: 10rpx;
}
.t-list image{
  width: 94rpx;
  height: 94rpx;
  margin: 20rpx auto;
  display: block;
  border-radius: 10rpx;
}
.t-list text{
  width: 100%;
  height: 47rpx;
  font-size: 24rpx;
  line-height: 47rpx;
  color: #666;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: block;
}

/** 一级分类 **/

.one-content{
  width:80%;
  height:100%;
  font-size:28rpx;
  box-sizing:border-box;
  display:inline-block;
  position:fixed;
  top:0;
  bottom:0;
  right:0;
  overflow-x:hidden;
  padding-bottom: 120rpx;
}
.cmd-list:first-child{
  margin-top: 5rpx;
}
.cmd-list{
  background-color:white;
  padding:10rpx;
  height: 160rpx;
  width: 540rpx;
  overflow: hidden;
  margin-left:20rpx;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
}
.cmd-img{
  width: 143rpx;
  height: 143rpx;
  margin: 9rpx;
  float: left;
  background-color: skyblue;
}
.cmd-img image{
  width: 100%;
  height: 100%;
}
.cmd-title {
    width: 358rpx;
}
.cmd-comm {
    float: left;
}
.str-product{
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    font-size: 24rpx;
    overflow: hidden;
    line-height: 30rpx;
    padding: 12rpx 0 0 14rpx;
    width: 375rpx;
    height: 60rpx;
}
.str-prices {
    color: #ff6a00;
    font-size: 28rpx;
    font-weight: bold;
    margin: 7rpx 0 0 10rpx;
}
.str-evaluate {
    font-size: 26rpx;
    color: #999;
    padding-left: 9rpx;
    float: left;
    width: 100%;
}
.fg{
    height: 42rpx;
    line-height: 42rpx;
    display: inline-block;
    padding-top: 5rpx;
    width: 156rpx;
    float: left;
    font-size: 24rpx;
}
.add-cart{
    display: inline-block;
    width: 43rpx;
    height: 43rpx;
    border: 1rpx solid #ff6a00;
    text-align: center;
    border-radius: 50%;
}
.add-cart image{
  margin-top: 4rpx;
  width: 34rpx;
  height: 34rpx;
}




/* 规格弹框 */
.spec-model{
    position: fixed;
    bottom: 0;
    background: white;
    width: 100%;
    padding: 0 30rpx;
    font-size: 32rpx;
    box-sizing: border-box;
    overflow-x: hidden;
    z-index:9999;
}

.spec-goods{
    padding: 15rpx 0 30rpx;
    float: left;
    width: 100%;
    border-bottom: 1px solid #f3f3f3;
}

.spec-goods-info{
    float: left;
    padding: 0 25rpx; 
    width: 490rpx;
}
.spec-goods-name{
    font-size: 30rpx;
    line-height: 35rpx;
    height: 70rpx;
    margin: 15rpx 20rpx 25rpx 0;
    overflow: hidden;
    text-overflow: ellipsis;
}
.spec-goods-price{
    color: #ff6a00;
    font-size: 30rpx;
    font-weight: bold;
}
.spec-goods-stock{
    margin-top: 10rpx;
    font-size: 26rpx;
    color: #999999;
}
.spec-img{
    float: left;
    height: 150rpx;
    width: 150rpx;
    margin-top:16rpx;
}
.spec-goods-info{
    float: left;
    padding: 0 25rpx; 
    width: 490rpx;
}
.spec-goods-name{
    font-size: 30rpx;
    line-height: 35rpx;
    height: 70rpx;
    margin: 15rpx 20rpx 25rpx 0;
    overflow: hidden;
    text-overflow: ellipsis;
}
.spec-goods-price{
    color: #ff6a00;
    font-size: 30rpx;
    font-weight: bold;
}
.spec-goods-stock{
    margin-top: 10rpx;
    font-size: 26rpx;
    color: #999999;
}
.spec-name{
    clear: both;
    padding: 20rpx 0;
    font-size: 30rpx;
}
.count{
    float: left;
    width: 184rpx;
    height: 50rpx;
    border: 1rpx solid #f3f3f3;
    font-size: 28rpx;
}
.count>view,.count>input{
    float: left;
    width: 60rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
}
.sub{
    border-right: 1px solid #f3f3f3;
}
.add{
    border-left: 1px solid #f3f3f3;
}
.spec-btn{
    color: #333;
    background-color: white;
    padding: 10rpx 10rpx;
    font-size: 26rpx;
    line-height: 28rpx;
    float: left;
    border: 1rpx solid #f3f3f3;
    margin: 4rpx 10rpx 4rpx 0;
    border-radius: 4rpx;
}
.spec-btn-click{
    color: white;
    background-color: #ff6a00;
    border: 1rpx solid #ff6a00;
}
.spec-cart-btns{
    background-color: #f8f8f8;
    margin:40rpx -30rpx 0;
    padding: 20rpx 34rpx;
    float: left;
    width: 100%;
    line-height: 80rpx;
}
.spec-cart-btn{
    float: left;
    width: 324rpx;
    font-size: 30rpx;
    text-align: center;
    color: white;
    border-radius: 10rpx;
}
.spec-buy{
    background-color: #ff6a00;
    margin-left: 34rpx;
}
.spec-cart-btn-lg{
    width: 614rpx;
}
.spec-cart-disable{
    background: #bbbbbb;
}
.spec-add-cart{
    background-color: #ffb03f;
}
.cover-layer{
    z-index:999;
}

.prom-info{
    margin: 10rpx 0;
    color: #ff6a00;
}
.prom-info>.prom-type{
    color: white;
    background-color: #ff6a00;
    margin-right: 14rpx;
    padding: 2rpx 8rpx;
    border-radius: 4rpx;
}
</style>